<?php
/**
 * Created by PhpStorm.
 * ApiUserModel: xiao
 * Date: 2018/2/7
 * Time: 16:40
 */

namespace App\Http\Logic\Api;


use App\Http\Common\Config\PlatformConfig;
use App\Http\Common\Utils\DataUtils;
use App\Http\Common\Utils\JUtils;
use App\Http\Common\Utils\TokenUtils;
use App\Http\Middleware\Api\CrossHttp;
use App\Http\Models\Api\ApiUserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Symfony\Component\VarDumper\Cloner\Data;
use Tymon\JWTAuth\Token;

class ApiUserLogic
{
    const key_user_open_id   = 'openId';
    const key_user_nickname  = 'nickname';
    const key_user_sex       = 'sex';
    const key_user_avatar    = 'avatar';


    /**
     *  微信登录接口
     * @return \Illuminate\Http\JsonResponse
     */
    public static function weChatLogin()
    {
        $platform = CrossHttp::$platform;

        if ($platform != PlatformConfig::PLATFORM_WE_CHAT) return JUtils::RE('参数错误');

        $openID = Input::get('openId', '');

        $userData = ApiUserModel::verifyUser($openID, $platform);
        if (empty($userData)) {                                     // 没有这个用户， 去注册这个用户

            $nickname   = Input::get(self::key_user_nickname);
            $sex        = Input::get(self::key_user_sex);
            $avatar     = Input::get(self::key_user_avatar);
            return self::_registerWeChat($openID, $nickname, $sex, $avatar);
        }

        $cacheUserData = ApiUserModel::createCacheData($userData);
        return TokenUtils::saveToken($cacheUserData);
    }


    private static function _registerWeChat($openId, $nickname,$sex, $avatar)
    {
        $insert = array(
            'wx_open_id'    => $openId,
            'nickname'      => $nickname,
            'sex'           => $sex,
            'avatar'        => $avatar,
            'create_time'   => time(),
        );

        try {

            $user = ApiUserModel::create($insert);
            $cacheUserData = ApiUserModel::createCacheData($user);

            return TokenUtils::saveToken($cacheUserData);

        } catch (\Exception $e) {

            return JUtils::RE('服务器繁忙，请稍后再试');
        }

    }

}